package com.boot4g.admin.security.bean;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * The class Rest client details service.
 *
 * @author paascloud.net @gmail.com
 */
@Slf4j
@Component("restClientDetailsService")
public class RestClientDetailsServiceImpl implements ClientDetailsService {

	private ClientDetailsService clientDetailsService;

//	@Autowired
//	private SecurityProperties securityProperties;

	/**
	 * Init.
	 */
	@PostConstruct
	public void init() {
		InMemoryClientDetailsServiceBuilder builder = new InMemoryClientDetailsServiceBuilder();
//		if (ArrayUtils.isNotEmpty(securityProperties.getOauth2().getClients())) {
//			for (OAuth2ClientProperties client : securityProperties.getOauth2().getClients()) {
				builder.withClient("cloud4g")
						//springboot升级为2.0之后.secret必须要加密.不然会注册失败
						.secret(new BCryptPasswordEncoder().encode("cloud4g"))
						.authorizedGrantTypes("refresh_token", "password", "client_credentials")
						.accessTokenValiditySeconds(7200)
						.refreshTokenValiditySeconds( 60 * 60 * 24 * 15)
						.scopes("all");
//			}
//		}
		try {
			clientDetailsService = builder.build();
		} catch (Exception e) {
			log.error("init={}", e.getMessage(), e);
		}

		//        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(firstDataSource);
//        clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
//        clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
//        clients.withClientDetails(clientDetailsService);
	}

	/**
	 * Load client by client id client details.
	 *
	 * @param clientId the client id
	 *
	 * @return the client details
	 *
	 * @throws ClientRegistrationException the client registration exception
	 */
	@Override
	public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
		return clientDetailsService.loadClientByClientId(clientId);
	}
}
